package jkgl.information;

import cn.hutool.core.exceptions.UtilException;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class FileUtils {
    /**
     * 解析在线图片路径转换为 MultipartFile 对象
     * @param fileName 携带后缀的文件名称
     * @param urlNet 文件在线访问链接(minio永久访问链接)
     * @return
     */
    public static MultipartFile urlNetToMultipartFile(String fileName, String urlNet) {
        try {
            // 将在线图片地址转换为URL对象
            URL url = new URL(urlNet);
            // 打开URL连接
            URLConnection connection = url.openConnection();
            // 转换为HttpURLConnection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            // 获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            // 读取输入流中的数据，并保存到字节数组中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            // 将字节数组转换为字节数组
            byte[] bytes = byteArrayOutputStream.toByteArray();
            // 创建ByteArrayInputStream对象，将字节数组传递给它
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            String suffix = fileName.split(".")[1];
//            FILE_CONTENT_TYPE content_type = FILE_CONTENT_TYPE.parseContentType(suffix);
            // 创建MultipartFile对象，将ByteArrayInputStream对象作为构造函数的参数
            MultipartFile multipartFile = null;
            return multipartFile;
        }catch (IOException ex){
            ex.printStackTrace();
            throw new UtilException("附件无效");
        }
    }
}